<template>
	<div class="registration-detail">
        <nav-header>
			<template slot="menuBefore">
				<li><router-link to="/life/dormitory/accommodation-registration" tag="a">住宿登记</router-link></li>
				<li class="gap">&gt;</li>
			</template>
			<li @click="goBack" style="cursor: pointer">{{roomTitle}}</li>
            <li class="gap" v-if="roomTitle2">&gt;</li>
			<li>{{roomTitle2}}</li>
		</nav-header>

        <div class="zh-table-open detail-import clear">
            <div class="zh-open-right fr">
                <el-button type="primary" @click="batchImport">批量导入</el-button>
            </div>
        </div>

        <div class="zh-table-contents" v-loading="loading.status" :element-loading-text="loading.txt">
            <el-table
                :data="listData"
                fixed
                border
                style="width: 100%">
                <el-table-column
                    prop="bed_number"
                    label="床位"
                    align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="user_number"
                    label="账号"
                    align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="user_name"
                    label="姓名"
                    align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="class_name"
                    label="班级"
                    align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="class_master"
                    label="班主任"
                    align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="student_number"
                    label="学号"
                    align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop=""
                    label="入住时间"
                    align="center"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{scope.row.check_in_time.split(' ')[0]}}
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    align="center"
                    :width="180">
                    <template slot-scope="scope">
                        <template v-if="scope.row.id">
                            <el-button @click="newRoom(scope.row, scope.$index)" type="text">编辑</el-button>
                            <el-button @click="changeRoom(scope.row)" type="text">调寝</el-button>
                            <el-button @click="deleteConfirm(scope.row.id)" type="text" class="delete-button">删除</el-button>
                        </template>
                        <el-button v-else @click="newRoom('add', scope.$index)" type="text">添加</el-button>
                        
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <el-dialog 
            title="调寝" 
            :visible.sync="exchangeVisible" 
            class="exchange-manage" 
            width="550px" 
            :before-close="cancelForm"
            :close-on-click-modal="false">
            <el-form :model="exchangeForm" :rules="rules" ref="exchangeForm" label-width="100px" class="demo-exchange-form">
                <el-form-item label="账号：">
                    <el-input v-model="exchangeForm.number" disabled></el-input>
                </el-form-item>
                <el-form-item label="姓名：">
                    <el-input v-model="exchangeForm.name" disabled></el-input>
                </el-form-item>
                <el-form-item label="原寝室：" class="room-box">
                    <el-select v-model="exchangeForm.building" placeholder="请选择宿舍楼" disabled>
                        <el-option v-for="(item, inx) in buildingList" :key="inx" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                    <el-select v-model="exchangeForm.floor" placeholder="请选择寝室" style="margin: 0 10px" disabled>
                        <el-option v-for="(item, inx) in DfloorList" :key="inx" :label="item.number" :value="item.id"></el-option>
                    </el-select>
                    <el-select v-model="exchangeForm.room" placeholder="请选择床位" disabled>
                        <el-option v-for="(item, inx) in DroomList" :key="inx" :label="item.bed_number" :value="item.bed_number"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="调整寝室：" class="room-box">
                    <el-form-item prop="building1">
                        <el-select v-model="exchangeForm.building1" placeholder="请选择宿舍楼" @change="getFloor" filterable>
                            <el-option v-for="(item, inx) in buildingList" :key="inx" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="floor1">
                        <el-select v-model="exchangeForm.floor1" placeholder="请选择寝室" @change="getRoom" filterable>
                            <el-option v-for="(item, inx) in floorList" :key="inx" :label="item.number" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="room1">
                        <el-select v-model="exchangeForm.room1" placeholder="请选择床位" filterable>
                            <el-option v-for="(item, inx) in roomList" :key="inx" :label="item.bed_number" :value="item.bed_number"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form-item>
            </el-form>
            
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="cancelForm" plain>取消</el-button>
                <el-button type="primary" @click="submitExchange('exchangeForm')">确定</el-button>
            </div>
        </el-dialog>

        <el-dialog 
            :title="recordTitle" 
            :visible.sync="recordVisible" 
            class="record-manage" 
            width="800px" 
            :before-close="cancelForm"
            :close-on-click-modal="false">
            <div>
                <div class="record-contet-head">
                    <div style="position:relative">
                        <span class="check-title">入住日期：</span>
                        <el-date-picker
                            v-model="checkDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            @change="changeDate"
                            :class="errorVisible ? 'error-input' : ''"
                            placeholder="请选择入住日期">
                        </el-date-picker>
                        <div class="error-title-date" v-show="errorVisible">请选择入住日期</div>
                    </div>
                    <div class="search-text">
						<el-input v-model="studentParam.keyword" placeholder="输入搜索内容" @keyup.enter.native="searchFunc"></el-input>
                        <div >
                            <el-cascader
                                placeholder="请选择班级"
                                v-model="studentParam.classId"
                                :options="gradeList"
                                @change="changeAddItem"
                                style="width: 100%">
                            </el-cascader>
                        </div>
                        <div>
                            <el-button type="primary" @click="searchFunc">搜索</el-button>
                            <el-button type="primary" @click="resetList">重置</el-button>
                        </div>
                    </div>
                </div>

                <div class="zh-table-contents" v-loading="loading1.status" :element-loading-text="loading1.txt">
                    <el-table
                        :data="studentList"
                        fixed
                        border
                        ref="multipleTable"
                        highlight-current-row
						@row-click="showStudentRadio"
                        style="width: 100%">
                        <el-table-column
							type="index"
							label="序号"
							width="50">
							<template slot-scope="scope">
								<el-radio class="radio" v-model="selStudent" :label="scope.$index">&nbsp;</el-radio>
							</template>
						</el-table-column>
                        <el-table-column
                            prop="user_number"
                            label="账号"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="true_user_name"
                            label="用户名"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop=""
                            label="真实姓名"
                            align="center"
                            show-overflow-tooltip>
                            <template slot-scope="scope">
                                {{scope.row.true_user_name ? scope.row.true_user_name : scope.row.user_name}}
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="class_name"
                            label="班级"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="class_master"
                            label="班主任"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                    </el-table>

                    <div class="table-pagination" v-show="studentParam.totalNumber > 10">
                        <el-pagination
                            @size-change="setCurrentSize"
                            @current-change="setCurrentPage"
                            :current-page="studentParam.pageIndex"
                            :page-sizes="[10, 20, 30, 40, 50, 100]"
                            :page-size="studentParam.pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="studentParam.totalNumber">
                        </el-pagination>
                    </div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="cancelForm" plain>取消</el-button>
                <el-button type="primary" @click="submitRecord('recordForm')">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            recordVisible: false, // 添加床位信息
            exchangeVisible: false, // 调寝是否弹窗
            errorVisible: false, // 错误提示
            isEditId: null, // 是否编辑状态
            roomIndex: null, // 床位号
            selStudent: '', // 选中学生
            selStudentId: '', // 选中学生 id
            roomTitle: '', // 寝室地址
            roomTitle2: '', // 寝室地址
            recordTitle: '添加', // 添加床位标题
            checkDate: undefined, // 入住日期
            listData: [], // 寝室床位列表
            buildingList: [], // 宿舍楼列表
            floorList: [], // 楼层列表
            DfloorList: [], // 楼层列表
            roomList: [], // 床位列表
            DroomList: [], // 床位列表
            studentList: [], // 学生列表
            gradeList: [], // 班级列表
            loading: { // 数据加载状态
                status: false,
                txt: '获取数据...'
            },
            loading1: { // 数据加载状态
                status: false,
                txt: '获取数据...'
            },
            exchangeForm: {
                id: null,
                number: '123',
                name: '345',
                building: 1,
                floor: 1,
                room: 1,
                building1: null,
                floor1: null,
                room1: null
            },
            studentParam: {
                keyword: '', // 学生列表搜索
                classId: [],
                pageIndex: 1,
                pageSize: 10,
                totalNumber: 0
            },
            rules: {
                building1: [
                    { required: true, message: '请选择宿舍楼', trigger: 'change' }
                ],
                floor1: [
                    { required: true, message: '请选择寝室', trigger: 'change' }
                ],
                room1: [
                    { required: true, message: '请选择床位', trigger: 'change' }
                ]
            },
            buildingId: null, // 宿舍楼 id
        }
    },
    created() {
        this.getList();
        this.getRoomInfo();
        this.getBuilding();
        this.getAllClass();
    },
    methods: {
        goBack() {
            sessionStorage.setItem('ldarId', this.buildingId);
            this.$router.push('/life/dormitory/accommodation-registration');
        },
        /**
         * 获取寝室信息
         */
        getRoomInfo() {
            let success = (res => {
                this.roomTitle = res.data.building_name;
                this.roomTitle2 = res.data.number;
                this.buildingId = res.data.building_id;
            })

            this.$ajax.get('api/dormitory/dormitory',{params: {id: this.$route.params.id}, func:{success: success}});
        },
        /**
         * 从组织架构中获取班级
         */
        getAllClass(){
            let success = (res1 => {
                let tempArr = [];
                let tempData = res1.data ? res1.data[0].children : [];

                if (!is_empty(tempData)) {
                    tempData.forEach((val, index) => {
                        let data2 = val.children;

                        if (!is_empty(data2)) {
                            tempArr.push({
                                value: val.id,
                                label: val.name,
                                children: []
                            })

                            data2.forEach((res, index2) => {
                                let data3 = res.children;
                                
                                if (!is_empty(data3)) {
                                    tempArr[index].children.push({
                                        value: res.id,
                                        label: res.name,
                                        children: []
                                    })

                                    data3.forEach((tex, index3) => {
                                        tempArr[index].children[index2].children.push({
                                            value: tex.id,
                                            label: tex.name,
                                        })
                                    })
                                } else {
                                    tempArr[index].children.push({
                                        value: res.id,
                                        label: res.name,
                                    })
                                }
                            })
                        } else {
                            tempArr.push({
                                value: val.id,
                                label: val.name,
                            })
                        }
                    })
                }

                this.gradeList = tempArr;
            });
            let orgParam = {
                status: [1, 2],
                data_type: 'manage_tree'
            }

            this.$ajax.get('api/org/org', {params: orgParam, func: {success: success}})
        },
        /**
         * 动态改变标签的名字
         * @param {Array} val 选中值的 id
         */
        changeAddItem(val) {
            if (val.length < 3) {
                this.studentParam.classId = [];
            }
        },
        /**
         * 获取寝室入住信息列表
         */
        getList() {
            this.loading.status = true;

            let success = (res => {
                this.loading.status = false;
                this.listData = res.data;
            })
            let params = {
                dormitory_id: this.$route.params.id,
                data_type: 2
            }

            this.$ajax.get('api/dormitory/dormitoryUser',{params: params, func:{success: success}});
        },
        /**
         * 获取宿管列表
         */
        getBuilding() {
            const success = (res => {
                this.buildingList = res.data;
            })

            this.$ajax.get('api/dormitory/dormitoryBuilding', {func: {success: success}})
        },
        /**
         * 获取楼层
         * @param {Number} val 宿舍楼id
         */
        getFloor(val) {
            this.floorList = [];
            this.roomList = [];
            this.exchangeForm.floor1 = '';
            this.exchangeForm.room1 = '';

            let success = (res => {
                this.floorList = res.data;
            })

            this.$ajax.get('api/dormitory/getDormitoryByBuildingId', {params: {building_id: val}, func:{success: success}});
        },
        /**
         * 获取床位
         * @param {Number} val 楼层id
         */
        getRoom(val) {
            let success = (res => {
                this.roomList = res.data;
            })

            let params = {
                dormitory_id: val,
                data_type: 2
            }

            this.$ajax.get('api/dormitory/dormitoryUser',{params: params, func:{success: success}});
        },
        /**
         * 获取楼层
         * @param {Number} val 宿舍楼id
         */
        getDFloor(val) {
            let success = (res => {
                this.DfloorList = res.data;
            })

            this.$ajax.get('api/dormitory/getDormitoryByBuildingId', {params: {building_id: val}, func:{success: success}});
        },
        /**
         * 获取床位
         * @param {Number} val 楼层id
         */
        getDRoom(val) {
            let success = (res => {
                this.DroomList = res.data;
            })
            let params = {
                dormitory_id: val,
                data_type: 2
            }

            this.$ajax.get('api/dormitory/dormitoryUser',{params: params, func:{success: success}});
        },
        /**
         * 获取学生列表 
         */
        getStudentList(val) {
            let success = (res => {
                this.studentList = res.data.data;
                this.studentParam.totalNumber = res.data.data_sum;

                if (this.isEdit) {
                    let flag = false;
                    let _inx;

                    !is_empty(this.studentList) && this.studentList.forEach((item, inx) => {
                        if (item.id === this.isEdit) {
                            flag = true;
                            _inx = inx;
                        }
                    })

                    if (flag) {
                        this.selStudent = _inx;
                    } else {
                        this.selStudent = '';
                    }
                } else {
                    this.selStudent = '';
                }
            })
            let params = {
                class_id: this.studentParam.classId.length === 3 ? this.studentParam.classId[2] : null,
                keyword: this.studentParam.keyword,
                page_index: this.studentParam.pageIndex,
                page_size: this.studentParam.pageSize,
                user_id : this.isEdit ? this.isEdit : null
            }

            this.$ajax.get('api/dormitory/noDormitoryUser',{params: params, func:{success: success}});
        },
        /**
         * 搜索列表
         */
        searchFunc() {
            this.studentParam.pageIndex = 1;
            this.getStudentList();
        },
        /**
         * 重置学生列表
         */
        resetList() {
            this.studentParam.keyword = '';
            this.studentParam.classId = [];
            this.studentParam.pageIndex = 1;
            this.studentParam.pageSize = 10;

            this.getStudentList();
        },
        /**
         * 单选框，选择点击的数据
         * @param {Object} row 当前行数据
         */
        showStudentRadio(row) {
            this.selStudent = this.studentList.indexOf(row);
            this.selStudentId = row.id;
        },
        /**
         * 添加/编辑寝室
         * @param {Number/String} val 记录id / 添加标识
         * @param {Number} inx 数组下标
         */
        newRoom(val, inx) {
            this.recordVisible = true;

            if (val === 'add') {
                this.isEditId = null;
                this.recordTitle = '添加';
                this.selStudentId = '';
                this.isEdit = null;
                this.roomIndex = this.listData[inx].bed_number;
                this.checkDate = new Date().toLocaleDateString().split('/').join('-');

                this.resetList();
            } else {
                this.isEditId = val.id;
                this.recordTitle = '编辑';
                this.checkDate = val.check_in_time;
                this.selStudentId = val.user_id;
                this.isEdit = val.user_id;
                this.roomIndex = val.bed_number;
                
                this.resetList();
            }
        },
        /**
         * 保存床位信息
         */
        submitRecord() {
            if (!this.checkDate) {
                return false;
            }

            const success = (res => {
                this.recordVisible = false;

                this.getList();
            })

            if (!this.isEditId) {
                let params = {
                    dormitory_id: this.$route.params.id, // 宿舍id
                    bed_number: this.roomIndex, // 床位号
                    check_in_time: this.checkDate, // 入住时间
                    user_id: this.selStudentId // 入住人id
                }
                 this.$ajax.post("api/dormitory/dormitoryUser", params, {func: {success: success}});
            } else {
                let params = {
                    id: this.isEditId,
                    bed_number: this.roomIndex, // 床位号
                    check_in_time: this.checkDate, // 入住时间
                    user_id: this.selStudentId // 入住人id
                }
                this.$ajax.put("api/dormitory/dormitoryUser", params, {func: {success: success}});
            }

        },
        /**
         * 跟换寝室
         * @param {Object} user_id 记录
         */
        changeRoom(obj) {
            let success = (res => {
                this.exchangeVisible = true;

                this.exchangeForm = {
                    id: obj.user_id,
                    number: res.data.user_number,
                    name: res.data.user_name,
                    building: parseInt(res.data.building_id),
                    floor: parseInt(res.data.floor_id),
                    room: obj.bed_number,
                    building1: null,
                    floor1: null,
                    room1: null
                }

                this.checkDate = obj.check_in_time;

                this.getDFloor(parseInt(res.data.building_id));
                this.getDRoom(parseInt(res.data.dormitory_id));

                this.$nextTick(() => {
                    this.$refs.exchangeForm.clearValidate();
                })
            })

            this.$ajax.get('api/dormitory/getDormitoryInfoByUser',{params: {user_id: obj.user_id}, func:{success: success}});
        },
        /**
         * 保存调寝
         * @param {String} formName 表单 ref
         */
        submitExchange(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let params = { // 需要宿舍楼 id， 没有入住时间
                        user_id: this.exchangeForm.id, // 入住人id
                        dormitory_id: this.exchangeForm.floor1, // 宿舍id
                        bed_number: this.exchangeForm.room1, // 床位号
                        check_in_time: this.checkDate, // 入住时间
                    }

                    const success = (res => {
                        this.exchangeVisible = false;

                        this.getList();
                    })

                    this.$ajax.put("api/dormitory/changeDormitoryUser", params, {func: {success: success}});
                } else {
                    return false;
                }
            });
        },
        /**
         * 关闭弹窗
         */
        cancelForm() {
            this.exchangeVisible = false;
            this.recordVisible = false;
        },
        /**
         * 确认是否删除入住信息
         * @param {Number} id 当前要删除入住信息的 id
         */
        deleteConfirm(id) {
            const yes = (res => {
                this.deleteList(id);
            })
            const cancel = (res => {})

            this.e_confirm({yes: yes, cancel: cancel, txt: '确定要删除该床位吗？删除将不可恢复'});
        },
        /**
         * 删除入住信息
         * @param {Number/Array} id 删除入住信息的 id
         */
        deleteList(id) {
            this.loading.status = true;

            let success = (res => {
                this.$message.success(res.msg);

                this.getList();
            });
            let fail = (res =>{
                this.$message.error(res.msg);

                this.getList();
            }) 
            
            this.$ajax.delete('api/dormitory/dormitoryUser', {params: {id}, func:{success: success, fail: fail}});
        },
        /**
         * 设置每页列表的数量
         * @param {Number} val 每页数据条数
         */
        setCurrentSize(val) {
            this.studentParam.pageIndex = 1;
            this.studentParam.pageSize = val;

            this.getStudentList();
        },
        /**
         * 设置当前列表的页数
         * @param {Number} val 页数
         */
        setCurrentPage(val) {
            this.studentParam.pageIndex = val;

            this.getStudentList();
        },
        /**
         * 验证入住日期是否必填
         */
        changeDate(val) {
            if (!val) {
                this.errorVisible = true;
            } else {
                this.errorVisible = false;
            }
        },
        /**
         * 批量导入
         */
        batchImport() {
            this.$router.push("/life/dormitory/registration-detail-import/" + this.$route.params.id)
        }
    },
}
</script>

<style lang="scss">
.registration-detail {
    .room-box {
        >div {
            display: flex;

            >.el-form-item:nth-child(2) {
                margin: 0 10px;
            }
        }
    }

    .detail-import {
        margin-bottom: 26px;
    }

    .record-contet-head {
        .check-title:before {
            content: '*';
            color: red;
            vertical-align: middle;
        }

        .error-title-date {
            position: absolute;
            left: 80px;
            padding-top: 4px;
            color: #f56c6c;
            font-size: 12px;
            line-height: 1;
        }

        .error-input input {
            border: 1px solid #f56c6c;
        }

        .search-text {
            display: flex;
            margin: 20px 0;

            >div:first-child {
                width: 300px;
            }

            >div:nth-child(2) {
                margin: 0 20px;
                width: 160px;
            }
        }
    }
}
</style>